import { arrayLastValue } from '/@/utils/twUtils';

/*
 * @Description: 流程设计模型部署表
 * @Author: DHL
 * @Date: 2022-08-23 15:26:03
 * @LastEditors: DHL
 * @LastEditTime: 2022-08-23 17:29:55
 */

import { defineComponent, computed, reactive, ref } from 'vue'
import { log } from '/@/utils/log'
import { ElMessage } from 'element-plus'
import { cloneDeep, assign } from 'lodash-es'
import { ActReModelModel } from '/@/api/flow/model/actReModelModel'
import { apiActReModelSave, apiActReModelUpdateById } from '/@/api/flow/actReModel'
import { apiFlowCategorySearchTree } from '/@/api/flow/flowCategory'

export default defineComponent({
  name: 'ActReModelForm',
  emits: ['refreshTableData'],
  setup(props, { emit, expose }) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////
    const dbFormRef = ref()
    const loading = ref(true)

    /**
     * 表单操作标记
     */
    const action = ref('add')

    /**
     * 显示弹框
     */
    const visible = ref(false)

    /**
     * 标题
     */
    const title = computed(() => {
      let rtn = ''
      switch (action.value) {
        case 'add':
          rtn = '新增'
          break
        case 'edit':
          rtn = '编辑'
          break
        default:
          rtn = '查看'
          break
      }
      return rtn
    })

    /**
     * 公共
     */
    const state = reactive({ category: '' })

    //////////////////////////////////////////////////
    // 表单
    //////////////////////////////////////////////////

    const defaultForm = {
      name: '',  // 名称
      key: '',  // 标识
      category: '',  // 分类
      description: '' // 描述
    }

    let dbForm = reactive<ActReModelModel>(cloneDeep(defaultForm))

    //////////////////////////////////////////////////
    // 表单验证规则
    //////////////////////////////////////////////////

    /**
     * 表单验证规则
     */
    const rules = reactive({
      name: [
        {
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }, {
          max: 255,
          message: '最多可输入255个字符',
          trigger: 'blur'
        }
      ],
      key: [
        {
          required: true,
          message: '请输入唯一编码',
          trigger: 'blur'
        }, {
          max: 255,
          message: '最多可输入255个字符',
          trigger: 'blur'
        }
      ],
      category: [
        {
          required: true,
          message: '请输入分类',
          trigger: 'blur'
        }, {
          max: 255,
          message: '最多可输入255个字符',
          trigger: 'blur'
        }
      ],
      createTime: [
        {
          required: true,
          message: '请选择创建时间',
          trigger: 'blur'
        }
      ],
      lastUpdateTime: [
        {
          required: true,
          message: '请选择最后更新时间',
          trigger: 'blur'
        }
      ],
      version: [
        {
          required: true,
          message: '请输入版本',
          trigger: 'blur'
        }
      ],
      deploymentId: [
        {
          required: true,
          message: '请输入部署ID',
          trigger: 'blur'
        }, {
          max: 64,
          message: '最多可输入64个字符',
          trigger: 'blur'
        }
      ]
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 打开弹框
     */
    function handleOpen(actionParam: string, rowParam?: ActReModelModel, categoryParams?: { category: string }) {
      visible.value = true
      loading.value = false
      action.value = actionParam

      handleSearchTree()

      if (['edit', 'view'].indexOf(actionParam) > -1 && rowParam) {
        assign(dbForm, cloneDeep(rowParam))
      } else {
        assign(state, categoryParams)
      }
    }

    /**
     * 关闭弹框
     */
    function handleClose() {
      assign(dbForm, cloneDeep(defaultForm))
      visible.value = false
    }

    /**
     * 提交表单
     */
    function handleSubmit(isContinue: boolean) {
      assign(dbForm, {
        category: arrayLastValue(state.category)
      })

      dbFormRef.value.validate((valid: boolean) => {
        if (valid) {
          if (action.value === 'add') {
            addFun(isContinue)
          } else {
            editFun()
          }
        } else {
          log.warn('流程设计模型部署表', '表单校验失败')
        }
      })
    }

    /**
     * 新增
     * @param isContinue 是否新增并继续
     */
    function addFun(isContinue: boolean) {
      loading.value = true
      apiActReModelSave(dbForm)
        .then((result) => {
          if (result?.success) {
            handleReset(!isContinue)
            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => { })
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 编辑
     * @returns
     */
    function editFun() {
      loading.value = true
      apiActReModelUpdateById(dbForm)
        .then((result) => {
          if (result?.success) {
            handleReset(true)
            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => { })
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 重置表单
     * @param isClosed 是否关闭弹框
     */
    function handleReset(isClosed: boolean) {
      assign(dbForm, cloneDeep(defaultForm))
      if (isClosed) {
        emit('refreshTableData')
        visible.value = false
      }
    }


    //////////////////////////////////////////////////
    // 流程分类树
    //////////////////////////////////////////////////

    const treeData = ref()

    /**
     * 查询流程分类树
     */
    function handleSearchTree() {
      apiFlowCategorySearchTree({}).then((result) => {
        treeData.value = result.treeData
      })
    }

    /**
     * 暴露函数
     */
    expose({ handleOpen })

    return {
      loading,
      visible,
      action,
      title,
      state,
      dbFormRef,
      dbForm,
      rules,
      handleOpen,
      handleClose,
      handleSubmit,
      handleReset,
      treeData
    }
  }
})
